<?php



/**
 * 73YC 购物流程
 * ============================================================================
 * * 版权所有 20013-* 梅州络客网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.alork.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: index.php 17217 2013-10-19 06:29:08Z liubo $
*/
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/classOrder.php');
/* 载入语言文件 */
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */
if (!isset($_REQUEST['step']))
{
    $_REQUEST['step'] = "cart";
}
/*------------------------------------------------------ */
//-- AJAX更新购物车
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'ajax_update_cart')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    if (isset($_REQUEST['goods_number']) && isset($_REQUEST['id']))
    {
        flow_update_cart(array($_REQUEST['id'] => $_REQUEST['goods_number']));
    }

    //查询更新过后的价格
    $sql = "SELECT c.goods_price, c.goods_number, c.market_price,g.shop_price AS price, g.preferential_price FROM " . $GLOBALS['ecs']->table('cart') . " AS c " .
        " LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g " .
        " ON c.goods_id = g.goods_id " .
        " WHERE  rec_id = " . $_REQUEST['id'];
    $goods = $GLOBALS['db']->getRow($sql);
    $result['preferential_price'] = $goods['preferential_price'];
    $result['goods_price'] = $goods['goods_price'];
    $result['price'] = $goods['price'];
    $result['sub'] = $goods['goods_price']*$goods['goods_number'];
    $result['preferential'] = ($goods['market_price']-$goods['goods_price'])*$goods['goods_number'];
    echo $json->encode($result);
    exit;
}
/*------------------------------------------------------ */
//-- AJAX计算结算金额
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'select_coupon')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $postOrder = !empty($_POST['order'])?$_POST['order']:'';//AJAX提交过来的订单信息
    /* 实例化订单操作类 */
    $cOrder = new classOrder;
    $return = array('error' => '0', 'message' => '', 'content' => 0);
    $address_id = !empty($postOrder['AddressId'])?$postOrder['AddressId']:"";//获取配送地址ID
    if(!empty($address_id)){
        $cOrder->getUserAddrList($address_id);
        $consignee = $cOrder->consignee;
    }
    else{
        $consignee = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:$_SESSION['consignee'];
    }
    /* 是否正常结算 */
    $rid =!empty($postOrder['Rid'])?$postOrder['Rid']:"";
    if (!empty($rid)) {
        $key = md5($rid);
        $rec_id = $_SESSION[$key];
    } else {



        die('结算数据出错！');
    }

    /* 对商品信息赋值 */
    //获取订单商品
    $cart_goods = $cOrder->getCartGoods($rec_id);

    if (empty($cart_goods))
    {   
        $return['error'] = "605";
        $return['message'] = "商品获取信息错误";
        echo $json->encode($result);
        exit;
    }
    else
    {

        /* 计算订单的费用 */
        $cOrder->orderInfo['pay_id']=$postOrder['PayId'];
        if (!empty($postOrder['CouponId'])) {
            $cOrder->coupon_id=implode(',',$postOrder['CouponId']);
        }
        $total = $cOrder->getTotal();
        $smarty->assign('total', $total);
        $return['content'] = $smarty->fetch('library/order_total.lbi');
    }
    echo $json->encode($return);
    exit;
}



/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */
assign_template();
assign_dynamic('flow');
$position = assign_ur_here(0, $_LANG['shopping_flow']);
$smarty->assign('page_title',       $position['title']);    // 页面标题
$smarty->assign('lang',             $_LANG); // 语言
$smarty->assign('data_dir',    DATA_DIR);       // 数据目录

// 判断STEP参数是否在允许范围内
$is_stpe=array( 'exchange', 'addToCart', 'checkout','select_shipping','select_payment','change_integral','change_bonus','check_integral','done','ajax_update_cart','drop_goods','clear','validate_bonus','follow_cart','cart','guadanle_add_cart', 'pay_success' , 'to_success' ,'ajax_cart_carousel','ajax_get_price');
if (!in_array($_REQUEST['step'], $is_stpe))
{
    ecs_header("Location: index.php\n");
    exit();
}

/*------------------------------------------------------ */
//-- 添加商品到购物车
/*------------------------------------------------------ */
if ($_REQUEST['step'] == 'addToCart')
{
    include_once('includes/cls_json.php');
    $result = array('error' => 0, 'message' => '', 'content' => '', 'goods_id' => '');
    $json  = new JSON;

    /* 格式化参数 */
    $_REQUEST['id'] = array_filter(explode('-', $_REQUEST['id']));
    $_REQUEST['ext'] = !empty($_REQUEST['ext'])?array_filter(explode('-', $_REQUEST['ext'])):'';
    $_REQUEST['attr'] = !empty($_REQUEST['attr'])?array_filter(explode('-', $_REQUEST['attr'])):'';
    $_REQUEST['number'] = !empty($_REQUEST['number'])?array_filter(explode('-', $_REQUEST['number'])):'';

    if (is_array($_REQUEST['id'])) {
        /* 存在购物信息 */
        foreach ($_REQUEST['id'] as $key => $value) {
            /* 格式化参数为商品数据 */
            $goodsList[$key]['id'] = $value;
            $goodsList[$key]['extension_code'] = !empty($_REQUEST['ext'][$key])?$_REQUEST['ext'][$key]:'';
            $goodsList[$key]['goods_attr_id'] = !empty($_REQUEST['attr'][$key])?array_filter(explode(',', $_REQUEST['attr'][$key])):'';
            $goodsList[$key]['goods_number'] =!empty($_REQUEST['number'][$key])?$_REQUEST['number'][$key]:1;
        }

        /* 实例化前端订单类 */
        $cOrder = new classOrder;
        /* 执行添加购物车操作 */
        $result = $cOrder->addToCart($goodsList);
        if ($result['error'] == 0) {
            /* 普通商品加入购物车 */
            $cart_info = insert_cart_info();
            $result['number'] = $cart_info[0];
            $result['content'] = "<span>购物车一共$cart_info[0]件商品，共计$cart_info[1]</span>";
        }

        die($json->encode($result));
    } else {
        /* 不存在购物信息，参数出错 */
        $result['error'] = 1;
        $result['message'] = '参数错误，请联系客服！';
        die($json->encode($result));
    }
}
/*------------------------------------------------------ */
//-- 订单确认页面
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'checkout')
{
    /* 取得购物类型 */
    $flow_type = isset($_SESSION['flow_type']) ? intval($_SESSION['flow_type']) : CART_GENERAL_GOODS;
    $user_id = $_SESSION['user_id'];
    $rec_id =!empty($_REQUEST['rec_id'])?$_REQUEST['rec_id']:""; // 勾选结算的rec_id
//     var_dump($rec_id);exit;
    $rid =!empty($_REQUEST['rid'])?$_REQUEST['rid']:""; // 记录结算商品rec_id的session键值
    if(empty($rid) && !empty($rec_id)){
        // 随机初始一个键值
        $rid = rand(100000000, 999999999);
        $key = md5($rid);
        // 记录勾选商品信息
        $_SESSION[$key] = $rec_id;
        header('Location:flow.php?step=checkout&rid=' . $rid);
    }
    /* 检查购物车中是否有商品 */
    elseif (empty($rid) && empty($rec_id)){
        header('Location:flow.php');
        exit;
    }
    /* 检查购物车中是否有商品 */
    elseif (!empty($rid)) {
        $key = md5($rid);
        $rec_id = $_SESSION[$key];
        $smarty->assign('rid', $rid);
    }

    /*
     * 如果没有登录则跳转到登录和注册页面
     */
   if (empty($_SESSION['user_id']))
    {
        /* 用户没有登录且没有选定匿名购物，转向到登录页面 */
        ecs_header("Location: user.php\n");
        exit;
    }

    /* 实例化订单操作类 */
    $cOrder  = new classOrder;
    $cOrder->time = $_CFG['systemTime'];


    // 获取用户收货地址列表
    $consignee_list = $cOrder->getUserAddrList();

    // 获取订单商品
    $cart_goods = $cOrder->getCartGoods($rec_id);

    if (empty($cart_goods)) {
        header('Location:flow.php');
        exit;
    }

    /* 判断是否存在预购商品弹出对应对话框有用 */
    foreach ($cart_goods as $key => $value) {
        if($value['extension_code'] == 'yugou'){
            $is_yugou = 1;
        }
    }

    $total = $cOrder->getTotal();

    /*判断是否进入活动时间*/
    if (!empty($_CFG['is_gift_start'])) {
        $smarty->assign('is_gift_start', 1); //活动是否开始
        $giftList = $cOrder->getGift($total['amount']);
        $giftTypeMax = 0;  // 最大赠品类型
        foreach ($giftList as $key => $value) {
            $giftType[$value['min_price']][] = $value;
            $giftTypeMax = max($value['min_price'], $giftTypeMax);
        }
        $smarty->assign('giftType', $giftType); //赠品类型
        $smarty->assign('giftTypeMax', $giftTypeMax); //赠品类型
        $smarty->assign('giftList', $giftList); //赠品
    }

    /*获取优惠卷信息*/
    $coupon = $cOrder->getCoupon($total['amount']);

    /*获取优惠金额*/
    foreach ($coupon as $key => $value) {
        if ($value['is_free']) {
            $coupon[$key]['discount']=$total['shipping_fee']-$cOrder->getShippingFee($total['goods_price'], $cOrder->orderInfo['pay_id'], $cOrder->consignee, $total['goods_weight'],$total['is_shipping'],$value['is_free']);
        }
        if ($value['discount']>0) {
            $coupon[$key]['discount'] = $total['goods_price']*(1-$value['discount']);
        }

    }
    $smarty->assign('coupon', $coupon);           //优惠卷列表

    // 地区选择器编号
    $smarty->assign('sn', 0);
    /* 取得购物流程设置 */
    $smarty->assign('config', $_CFG);
    $smarty->assign('is_yugou', $is_yugou);//判断是否预购商品
    $smarty->assign('goods_list', $cart_goods);           //购物车商品列表
    $smarty->assign('consignee_list', $consignee_list); // 收货信息列表
    $smarty->assign('total', $total); // 费用信息
    $smarty->assign('consignee', $cOrder->consignee); // 默认收货信息
    /* 保存 session */
    $_SESSION['flow_order'] = $order;
    $smarty->assign('no_nav', 1); //用于判断头部是否隐藏导航
}
/*------------------------------------------------------ */
//-- 改变支付方式
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'select_payment')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;
    /* 实例化订单操作类 */
    $cOrder = new classOrder;
    $result = array('error' => '', 'content' => '', 'need_insure' => 0, 'payment' => 1);
    $address_id = !empty($_REQUEST['address_id'])?$_REQUEST['address_id']:"";//获取配送地址ID
    if(!empty($address_id)){
        $cOrder->getUserAddrList($address_id);
        $consignee = $cOrder->consignee;
        $smarty->assign('address_id', $address_id);
    }
    else{
        $consignee = !empty($_REQUEST['consignee'])?$_REQUEST['consignee']:$_SESSION['consignee'];
    }
    /* 是否正常结算 */
    $rid =!empty($_REQUEST['rid'])?$_REQUEST['rid']:"";
    if (!empty($rid)) {
        $key = md5($rid);
        $rec_id = $_SESSION[$key];
        $smarty->assign('rid', $rid);
    } else {
        die('结算数据出错！');
    }

    /* 对商品信息赋值 */
    //获取订单商品
    $cart_goods = $cOrder->getCartGoods($rec_id);

    if (empty($cart_goods))
    {
        $result['error'] = $_LANG['no_goods_in_cart'];
    }
    else
    {
        /* 取得订单信息 */
        $order = $cOrder->orderInfo;
        $order['pay_id'] = intval($_REQUEST['payment']);
        /* 支付信息 */
        $payment_info = payment_info($order['pay_id']);
        $result['pay_code'] = $payment_info['pay_code'];
        /* 保存 session */
        $cOrder->orderInfo = $order;

        /* 计算订单的费用 */
        $total = $cOrder->getTotal();
        $smarty->assign('total', $total);

        $result['content'] = $smarty->fetch('library/order_total.lbi');
    }
    echo $json->encode($result);
    exit;
}
/*------------------------------------------------------ */
//-- 完成所有订单操作，提交到数据库
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'done')
{
    include_once(ROOT_PATH . 'includes/lib_clips.php');
    include_once(ROOT_PATH . 'includes/lib_payment.php');
    include_once(ROOT_PATH . 'includes/classCounter.php');
    include_once(ROOT_PATH . 'includes/cls_json.php');
    include_once(ROOT_PATH . 'includes/classLock.php');
    /* 实例化订单操作类 */
    $cOrder = new classOrder;
    $json   = new JSON;
    $lock   = new classLock;

    /*初始化返回信息*/
    $result = array();
    $result['error']   = 0;
    $result['message'] = '';
    $result['content'] = '';



    /*判断用户是否登录*/
    if (empty($_SESSION['user_id'])) {
        $result['error']   = 600;
        $result['message'] = '请登录后再操作';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }
    $lock->lock($_SESSION['user_id']);
    /*获取订单信息*/
    $postOrder = !empty($_POST['order'])?$_POST['order']:'';//AJAX提交过来的信息
    if (empty($postOrder)) {
        $result['error']   = 401;
        $result['message'] = '订单信息为空';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }

    /*检查是否有选择商品*/
    $rid =!empty($postOrder['Rid'])?$postOrder['Rid']:"";
    if (!empty($rid)) {
        $key = md5($rid);
        $recId = $_SESSION[$key];
    }
    if (empty($recId)) {
        $result['error']   = 605;
        $result['message'] = '商品获取信息错误';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }
    /* 检查勾选商品是否存在 */
    $cartGoods = $cOrder->getCartGoods($recId);
    if (empty($cartGoods)) {
        $result['error']   = 605;
        $result['message'] = '结算商品不存在';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }
    /*检查地址是否为空*/
    $addressId = !empty($postOrder['AddressId'])?intval($postOrder['AddressId']):"";

    /*检查是否有配送地址*/
    if (!empty($addressId)) {
        /*获取地址信息*/
        $cOrder->getUserAddrList($addressId);
        $consignee = $cOrder->consignee;
        if (empty($consignee)) {
            $result['error']   = 603;
            $result['message'] = '获取地址信息错误';
            $result['content'] = '';
            echo $json->encode($result);
            exit;
        }
    } else {
        $result['error']   = 603;
        $result['message'] = '地址信息错误';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }
    $payId = !empty($postOrder['PayId'])?intval($postOrder['PayId']):"";
    // 检查是否有选择支付方式
    if (empty($payId)) {
        $result['error']   = 604;
        $result['message'] = '没有选择支付方式';
        $result['content'] = '';
        echo $json->encode($result);
        exit;
    }
    /* 支付方式 */
    if ($payId > 0)
    {
        $payment = payment_info($payId);
        if($payment['pay_name']){
            $order['pay_name'] = addslashes($payment['pay_name']);
        }else{
            $result['error']   = 604;
            $result['message'] = '支付方式不存在';
            $result['content'] = '';
            echo $json->encode($result);
            exit;
        }
    }
    /* 实例化订数器操作类 */
    $c = new classCounter;
    /* 尝试添加计数器 */
    $c->addCounter('orderSum');
    /* 计数器加1 */
    $runSum = $c->inCounter('orderSum');
    if (!empty($runSum) && $runSum >= $_CFG['orderMaxNum']) {
        $result['error']   = 610;
        $result['message'] = '服务器繁忙请稍后再试';
        $result['content'] = '';
        goto result;
    }
    /* 执行过程 */
    /*重组商品筛选活动商品*/
    foreach ($cartGoods as $key => $value) {
        if ($value['extension_code'] == 'limit' || $value['extension_code'] == 'libao' || $value['extension_code'] == 'gift' || $value['extension_code'] == 'buyone') {
            # code...
        }
        else{
            $cartGoodsCommon[$key] = $value;
        }
    }
    /*预减库存库存不足返回错误*/
    if (!empty($cartGoodsCommon)) {
        $run = $GLOBALS['virtualStock']->outStockList($cartGoodsCommon);
        if (!$run) {
            $result['error']   = 602;
            $result['message'] = '库存不足是否返回购物车操作';
            $result['content'] = '';
            goto result;
        }
    }

    /*运行业务*/
    $user_id = $_SESSION['user_id'];

    /*初始订单基本信息*/
    $order = array(
        'shipping_id'     => 13,
        'shipping_name'   => '速递',
        'pay_id'          => $payId,
        'pay_name'        => addslashes($payment['pay_name']),
        'postscript'      => trim($postOrder['Message']),
        'user_id'         => $user_id,
        'add_time'        => time(),
        'order_status'    => OS_UNCONFIRMED,
        'shipping_status' => SS_UNSHIPPED,
        'pay_status'      => PS_UNPAYED,
        'country'         => 1,
        'province'        => $consignee['province'],
        'city'            => $consignee['city'],
        'district'        => $consignee['district'],
        'area_id'         => 3,
        'consignee'       => $consignee['consignee'],
        'address'         => $consignee['address'],
        'mobile'          => $consignee['mobile'],
        'agency_id'       => 3,
        );



    $cOrder->orderInfo = $order;
    /*使用优惠卷*/
    if (!empty($postOrder['CouponId'])) {
        $order['coupon_id'] = implode(',',$postOrder['CouponId']);
        $cOrder->coupon_id  = $order['coupon_id'];
    }
    /* 订单中的总额 */
    $total = $cOrder->getTotal();
    
    $order['discount'] = $total['discount'];
    $order['is_free'] = $total['is_free'];
    $order['goods_amount'] = $total['goods_price'];
    $order['shipping_fee'] = $total['shipping_fee']; // 配送费用
    $order['pay_fee']      = $total['pay_fee'];
    $order['cod_fee']      = $total['cod_fee'];
    $order['order_amount'] = number_format($total['amount'], 2, '.', '');
    /* 如果订单金额为0（使用余额或积分或红包支付），修改订单状态为已确认、已付款 */
    if ($order['order_amount'] <= 0)
    {
        $order['order_status'] = OS_CONFIRMED;
        $order['confirm_time'] = gmtime();
        $order['pay_status']   = PS_PAYED;
        $order['pay_time']     = gmtime();
        $order['order_amount'] = 0;
    }
    /* 更新订单信息 */
    $cOrder->orderInfo = $order;
    /*使用优惠卷*/
    if (!empty($order['coupon_id'])) {
        $cOrder->useCoupon($order['coupon_id']);//标记优惠卷为已使用
    }
    /* 处理赠品信息 */
    if (!empty($cOrder->orderInfo) && !empty($postOrder['gift'])) {
        if (!$lock->lock(md5('gift' . $postOrder['gift']))) {
            $result['error']   = 601;
            $result['message'] = '赠品处理出错，请稍候再提交！';
            $result['content'] = '';
            goto result;
        }
        $sql = 'SELECT min_price, parent_id, original_price, name FROM ' . $ecs->table('activity') . ' WHERE parent_id = ' . intval($postOrder['gift']);
        $giftInfo = $db->getRow($sql);
        if (!empty($giftInfo) && $order['order_amount'] >= $giftInfo['min_price']) {
            // 查询赠品数量
            $sql = 'SELECT valid_number FROM ' . $ecs->table('activity_stock') . ' WHERE parent_id = ' . intval($postOrder['gift']);
            $giftInfo['valid_number'] = $db->getOne($sql);
            if (!empty($giftInfo['valid_number'])) {
                // 如果存在可用数量则加入订单商品信息
                $cOrder->goodsList[] = array(
                    'goods_id'       => '0',
                    'goods_thumb'    => '',
                    'goods_name'     => $giftInfo['name'],
                    'goods_sku'      => 0,
                    'goods_number'   => 1,
                    'market_price'   => $giftInfo['original_price'],
                    'goods_price'    => 0,
                    'goods_attr'     => '',
                    'goods_attr_sku' => 0,
                    'is_real'        => 1,
                    'extension_code' => 'gift',
                    'parent_id'      => $giftInfo['parent_id'],
                    'is_gift'        => 1,
                    'goods_attr_id'  => 0,
                    );
                $sql = 'UPDATE ' . $ecs->table('activity_stock') . ' SET valid_number = valid_number - 1 WHERE parent_id = ' . $giftInfo['parent_id'];
                $db->query($sql);
            }
        }
        $lock->unlock(md5('gift' . $postOrder['gift']));
    }

    /* 提交订单 */
    $result = $cOrder->orderDone();
    if ($result !== false) {
        goto result;
    } else {
        $result['error']   = 610;
        $result['message'] = '服务器出错请联系客服处理！';
        $result['content'] = '';
        goto result;
    }
    /* 返回json状态及信息 */
    result:
    $lock->unlock($_SESSION['user_id']);
    /* 计数器减1 */
    $c->deCounter('orderSum');
    echo $json->encode($result);
    exit;
}

/*------------------------------------------------------ */
//-- 货到付款订单完成
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'to_success')
{
    include_once('includes/lib_transaction.php');
    $smarty->assign('no_nav', 1); //用于判断头部是否隐藏导航
    $order_id = !empty($_REQUEST['order_id'])?$_REQUEST['order_id']:'';
    if ($order_id) {
        $order = order_info($order_id);
    }
    $smarty->assign('order', $order);
    /* 广告位 */
    $ad = get_ad(4);
    $smarty->assign('ad', $ad);
}






/*------------------------------------------------------ */
//-- 支付宝确认订单完成
/*------------------------------------------------------ */
elseif ($_REQUEST['step'] == 'pay_success')
{
    include_once('includes/lib_transaction.php');
    /* 用户信息 */
    $info = get_user_head_rank();
    /* 获得最后一条成功的订单（且未评价）的商品金额 */
    $sql = "SELECT goods_amount, order_id FROM " . $ecs->table('order_info') . 
    " WHERE `user_id` =".$_SESSION['user_id']." AND `order_status` ='5' AND `pay_status` ='2' AND `comment`='0'" . 
    " ORDER BY order_id ASC";
    $row = $db->getRow($sql);
    $info['points'] = sprintf('%.0f', $row['goods_amount']);
    $info['href']  = (isset($row['order_id']) && !empty($row['order_id'])) ?  '/comments.php?act=comment&order_id=' . $row['order_id'] : 'javascript:void(0)';

    $smarty->assign('info', $info);
    /* 广告位 */
    $ad = get_ad(4);
    $smarty->assign('ad', $ad);
}


/*------------------------------------------------------ */
//-- AJAX获取购物车中所有商品的总价
/*------------------------------------------------------ */

// elseif($_REQUEST['step'] == 'ajax_get_price')
// {
//     require(ROOT_PATH . 'includes/cls_json.php');
//     $json = new JSON;

//     //查询购物车的中所有商品的数量，价格
//     $sql = "SELECT goods_number, goods_price FROM " . $GLOBALS['ecs']->table('cart') .
//         " WHERE user_id = " . $_REQUEST['user_id'];
//     $goods = $GLOBALS['db']->getAll($sql);

//     echo $json->encode($goods);
//     exit;
// }

/*------------------------------------------------------ */
//-- AJAX购物车轮播内容替换
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'ajax_cart_carousel')
{
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;

    if ($_REQUEST['thisItem'] == "guessYouLike"){
        $guessYouLike = guessYouLike();        //获取猜你喜欢商品
        $smarty->assign('carousel_list',$guessYouLike);
    }else if($_REQUEST['thisItem'] == "recentlyViewed"){
        $get_history = get_history();       //历史记录商品
        if(count($get_history)<15){
            $recentlyViewed = recentlyViewed(); //精品推荐商品
            $combiningArray = array_merge($get_history,$recentlyViewed); //合并商品
            $smarty->assign('carousel_list',$combiningArray);
        }
        else{
            dump($get_history);
            $smarty->assign('carousel_list',$get_history);
        }

    }else if($_REQUEST['thisItem'] == "myCollection"){
        $user_id = $_SESSION['user_id'];
        if($user_id == 0){
            $user_id = "1";
            $smarty->assign('user_id',$user_id);
        }else{
            $myCollection = myCollection($user_id);//我的收藏商品
            foreach ($myCollection as $key => $value) {
                $i++;
            }
            if(!$myCollection){
                $kong = "1";
                $smarty->assign('kong',$kong);
            }else if($i > 0 && $i < 6){
                $one = "1";
                $smarty->assign('one',$one);
                $smarty->assign('carousel_list',$myCollection);
            }else if($i > 5 && $i < 11){
                $two = "2";
                $smarty->assign('two',$two);
                $smarty->assign('carousel_list',$myCollection);
            }else if($i > 10){
                $three = "3";
                $smarty->assign('three',$three);
                $smarty->assign('carousel_list',$myCollection);
            }
        }
    }
    $cart_carousel = $smarty->fetch("library/cart_carousel_list.lbi");
    echo $json->encode($cart_carousel);
    exit;
}


/*------------------------------------------------------ */
//-- 删除购物车中的商品
/*------------------------------------------------------ */

elseif ($_REQUEST['step'] == 'drop_goods')
{
    if($_REQUEST['mode']=='all'){
        $rec_id = array_filter(explode('-',$_GET['id']));
        $cOrder = new classOrder;
        $cOrder->delCartGoods($rec_id);
        ecs_header("Location: flow.php\n");
        exit;
    }else{
        $rec_id = intval($_GET['id']);
        $cOrder = new classOrder;
        $cOrder->delCartGoods($rec_id);
        ecs_header("Location: flow.php\n");
        exit;
    }
}

// 购物车页面
elseif($_REQUEST['step'] == 'cart')
{
    /* 实例化订单类 */
    $cOrder = new classOrder;
    $cOrder->time = $_CFG['systemTime'];
    /* 取得猜你喜欢商品 */
    $guessYouLike = guessYouLike();
    $smarty->assign('is_yugou',$_CFG['is_yugou']); //判断活动是否开始
    $smarty->assign('is_gift_start', $_CFG['is_gift_start']); //赠品是否开始
    $smarty->assign('goods_list', $cOrder->getCartGoods());   //购物车商品列表
    $smarty->assign('guessYouLike', $guessYouLike); //猜你喜欢商品列表
    $smarty->assign('no_nav', 1); //用于判断头部是否隐藏导航
}

$smarty->assign('step',            $_REQUEST['step']);
assign_dynamic('shopping_flow');
$smarty->display('flow.dwt');

/*------------------------------------------------------ */
//-- PRIVATE FUNCTION
/*------------------------------------------------------ */

/**
 * 更新购物车中的商品数量
 *
 * @access  public
 * @param   array   $arr
 * @return  void
 */
function flow_update_cart($arr)
{
    /* 处理 */
    foreach ($arr AS $key => $val)
    {
        $val = intval(make_semiangle($val));
        if ($val <= 0 || !is_numeric($key))
        {
            continue;
        }

        //查询：
        $sql = "SELECT gs.goods_number AS goods_stock, c.goods_id, c.goods_attr_id, c.product_id, c.extension_code FROM " .$GLOBALS['ecs']->table('cart').
               " c LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON(gs.goods_id = c.goods_id AND gs.goods_attr_id = c.goods_attr_id AND gs.area_id = c.area_id) ".
               " WHERE c.rec_id='$key' AND c.user_id = '{$_SESSION['user_id']}'";
        $goods = $GLOBALS['db']->getRow($sql);

        //订货数量大于0
        if ($val > 0)
        {
            if($val <= $goods['goods_stock'])
            {
                $attr_id    = empty($goods['goods_attr_id']) ? array() : explode(',', $goods['goods_attr_id']);
                $goods_price = get_final_price($goods['goods_id'], $val, true, $attr_id);

                //更新购物车中的商品数量
                if($goods_price){
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val', goods_price = '$goods_price' WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
                }else{
                    $sql = "UPDATE " .$GLOBALS['ecs']->table('cart').
                            " SET goods_number = '$val' WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
                }
            }
        }
        //订货数量等于0
        else
        {
            $sql = "DELETE FROM " .$GLOBALS['ecs']->table('cart').
                " WHERE rec_id='$key' AND user_id = '{$_SESSION['user_id']}'";
        }

        $GLOBALS['db']->query($sql);
    }

    /* 删除所有赠品 */
    // $sql = "DELETE FROM " . $GLOBALS['ecs']->table('cart') . " WHERE session_id = '" .SESS_ID. "' AND is_gift <> 0";
    $GLOBALS['db']->query($sql);
}

/**
 * 获得广告位
 *
 * @access  private
 * @return  array
 */
    
    function get_ad($position_id = 0){
        if(!$position_id) return false;
        $position_id = intval($position_id);
        $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('ad') . " WHERE position_id = '$position_id' ORDER BY ad_name ASC ";
        return $GLOBALS['db']->getRow($sql);
    }


/**
 * 获得猜你喜欢的商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function guessYouLike()
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb , g.goods_img, g.is_hot,gt.goods_attr_id, ' .
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " .
        ' FROM '. $GLOBALS['ecs']->table('goods') . 'AS g ' .
        " LEFT JOIN ". $GLOBALS['ecs']->table('goods_attr') . 'AS gt  ON gt.goods_id = g.goods_id' .
        " WHERE g.is_hot = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 group by g.goods_id ORDER BY RAND() LIMIT 15";
    $res = $GLOBALS['db']->query($sql);
    $arr = array();
    $i=0;
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$i]['goods_id']         = $row['goods_id'];
        $arr[$i]['goods_name']       = $row['goods_name'];
        $arr[$i]['shop_price']       = price_format($row['shop_price']);
        $arr[$i]['promote_price']    = ($row['promote_price'] > 0) ? price_format($row['promote_price']) : '';
        $arr[$i]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$i]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$i]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$i]['is_hot']           = $row['is_hot'];
        $arr[$i]['is_attr']          = empty($row['goods_attr_id'])?0:1;
        $arr[$i++]['counts']         = $row['counts'];
    }
    return $arr;

}


/**
 * 取得最近浏览补充商品--精品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function recentlyViewed()
{
    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb ,gt.goods_attr_id, g.goods_img, g.is_best, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
        " LEFT JOIN ". $GLOBALS['ecs']->table('goods_attr') . 'AS gt  ON gt.goods_id = g.goods_id' .
        " WHERE g.is_best = 1 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 group by g.goods_id ORDER BY RAND() LIMIT 15";
    $res = $GLOBALS['db']->query($sql);
    
    $arr = array();
    $i=0;
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
        $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
        $arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
        $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$row['goods_id']]['is_attr']          = empty($row['goods_attr_id'])?0:1;
        $arr[$row['goods_id']]['counts']           = $row['counts'];
    }
    return $arr;
}

/**
 * 取得我的收藏产品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function myCollection($user_id)
{

    $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price, g.goods_thumb ,gt.goods_attr_id, g.goods_img, g.promote_start_date,gt.goods_attr_id, g.promote_end_date, c.rec_id, c.is_attention, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM ' . $GLOBALS['ecs']->table('collect_goods') . ' AS c' . 
        ' LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .  
        " ON g.goods_id = c.goods_id " . 
        " LEFT JOIN ". $GLOBALS['ecs']->table('goods_attr') . 'AS gt  ON gt.goods_id = g.goods_id' .
        " WHERE c.user_id = '$user_id' AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 group by g.goods_id ORDER BY RAND() LIMIT 15";
    $res = $GLOBALS['db']->query($sql);
    
    $arr = array();
    $i=0;
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $arr[$i]['goods_id']         = $row['goods_id'];
        $arr[$i]['goods_name']       = $row['goods_name'];
        $arr[$i]['shop_price']       = price_format($row['shop_price']);
        $arr[$i]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
        $arr[$i]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $arr[$i]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
        $arr[$i]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
        $arr[$i]['is_attr']          = empty($row['goods_attr_id'])?0:1;
        $arr[$i++]['counts']         = $row['counts'];
    }
    return $arr;    
}

/**
 * 取得历史记录商品
 *
 * @access  public
 * @param   string  $children
 * @return  array
 */
function get_history()
{
    $str = '';
    if (!empty($_COOKIE['ECS']['history'])){

        $where = db_create_in($_COOKIE['ECS']['history'], 'g.goods_id');
        $sql = 'SELECT g.goods_id, g.goods_name, g.shop_price, g.promote_price,gt.goods_attr_id, g.goods_thumb ,gt.goods_attr_id, g.goods_img, g.promote_start_date, g.promote_end_date, c.rec_id, c.is_attention, ' . 
        "(select count(1) from " . $GLOBALS['ecs']->table('comment') . " WHERE goods_id = g.goods_id) as counts " . 
        ' FROM ' . $GLOBALS['ecs']->table('collect_goods') . ' AS c' . 
        ' LEFT JOIN ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
        " ON g.goods_id = c.goods_id " . 
        " LEFT JOIN ". $GLOBALS['ecs']->table('goods_attr') . 'AS gt  ON gt.goods_id = g.goods_id' . 
        " WHERE $where AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 group by g.goods_id ORDER BY RAND() LIMIT 15";

        $res = $GLOBALS['db']->query($sql);
        $arr = array();
        $i=0;
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $arr[$row['goods_id']]['goods_id']         = $row['goods_id'];
            $arr[$row['goods_id']]['goods_name']       = $row['goods_name'];
            $arr[$row['goods_id']]['shop_price']       = price_format($row['shop_price']);
            $arr[$row['goods_id']]['promote_price']    = ($promote_price > 0) ? price_format($promote_price) : '';
            $arr[$row['goods_id']]['goods_thumb']      = get_image_path($row['goods_id'], $row['goods_thumb'], true);
            $arr[$row['goods_id']]['goods_img']        = get_image_path($row['goods_id'], $row['goods_img']);
            $arr[$row['goods_id']]['url']              = build_uri('goods', array('gid'=>$row['goods_id']), $row['goods_name']);
            $arr[$row['goods_id']]['is_attr']          = empty($row['goods_attr_id'])?0:1;
            $arr[$row['goods_id']]['counts']           = $row['counts'];
        }
        return $arr;
    }
}

?>

